const config = require('../util/config'),
    log = require('../util/log'),
    ChromeMng = require('./chromeMng1/ChromeMng'),
    logger = require('log4js').getLogger()

var chromeMngs = [], jdChromeMngs = [], wechatChromeMngs = [
    //new ChromeMng(
    // {
    //     port: 9223,
    //     host: '10.0.75.1',
    //     type: 'wechat'
    // })
]

if (config.domain == '') {
    chromeMngs.push(new ChromeMng({
        port: 9222,
        //host: '172.17.0.1',
        type: 'taobao'
    }))
    jdChromeMngs.push(new ChromeMng({
        port: 9223,
        //host: '172.17.0.1',
        type: 'jd'
    }))
} else if (config.domain == 'zoro.site') {
    chromeMngs.push(new ChromeMng({
        port: 9222
    }))
}

function getChromeMng(chromeMngs, obj) {
    if (chromeMngs.length == 0) {
        return new Promise((resolve, reject) => {
            reject('系统繁忙')
        })
    }
    obj = obj || {}
    obj.times = (obj.times || 0) + 1
    logger.debug('[' + __filename + ':' + __line + '] getting chromeMng', chromeMngs[0].type, obj.times)
    if (obj.times > config.chromeMaxTimes) {
        return new Promise((resolve, reject) => {
            reject('系统繁忙')
        })
    }
    if (obj.index || obj.index === 0) {
        var i = obj.index
        if (!chromeMngs[i].busy) {
            if (!chromeMngs[i].client) {
                //   chromeMngs[i].connect()
            } else {
                chromeMngs[i].busy = true
                return new Promise(resolve => {
                    resolve(chromeMngs[i])
                })
            }
        }
    } else {
        for (var i = 0; i < chromeMngs.length; i++) {
            if (!chromeMngs[i].busy) {
                if (!chromeMngs[i].client) {
                    //   chromeMngs[i].connect()
                    continue
                }
                chromeMngs[i].busy = true
                return new Promise(resolve => {
                    resolve(chromeMngs[i])
                })
            }
        }
    }
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            getChromeMng(chromeMngs, obj).then(result => {
                resolve(result)
            }, result => {
                reject(result)
            })
        }, 1000)
    })
}

exports.getTaobaoKeyWords = obj => {
    return new Promise((resolve, reject) => {
        getChromeMng(chromeMngs).then(chromeMng => {
            chromeMng.getTaobaoKeyWords(obj).then(result => {
                chromeMng.busy = false
                resolve(result)
            }, result => {
                chromeMng.busy = false
                reject(result)
            })
        }, result => {
            reject(result)
        })
    })
}

exports.getTaobaoItems = obj => {
    return new Promise((resolve, reject) => {
        getChromeMng(chromeMngs).then(chromeMng => {
            chromeMng.getTaobaoItems(obj).then(result => {
                chromeMng.busy = false
                resolve(result)
            }, result => {
                chromeMng.busy = false
                reject(result)
            })
        }, result => {
            reject(result)
        })
    })
}

exports.loginTaobao = obj => {
    var promises = []
    for (var i = 0; i < chromeMngs.length; i++) {
        promises.push(new Promise(resolve => {
            getChromeMng(chromeMngs, {
                index: i
            }).then(chromeMng => {
                chromeMng.loginTaobao().then(result => {
                    chromeMng.busy = false
                    resolve()
                }, result => {
                    chromeMng.busy = false
                    resolve()
                })
            }, result => {
                resolve()
            })
        }))
    }
    return new Promise((resolve, reject) => {
        Promise.all(promises).then(result => {
            resolve()
        })
    })
}

exports.getTaobaoAdvLink = obj => {
    return new Promise((resolve, reject) => {
        getChromeMng(chromeMngs).then(chromeMng => {
            chromeMng.getTaobaoAdvLink(obj).then(result => {
                chromeMng.busy = false
                resolve(result)
            }, result => {
                chromeMng.busy = false
                reject(result)
            })
        }, result => {
            reject(result)
        })
    })
}

exports.checkLoginTaobao = obj => {
    var promises = []
    for (var i = 0; i < chromeMngs.length; i++) {
        promises.push(new Promise(resolve => {
            getChromeMng(chromeMngs, {
                index: i
            }).then(chromeMng => {
                chromeMng.checkLoginTaobao().then(result => {
                    chromeMng.busy = false
                    resolve(result ? 1 : -1)
                }, result => {
                    chromeMng.busy = false
                    resolve(0)
                })
            }, result => {
                resolve(0)
            })
        }))
    }
    return new Promise((resolve, reject) => {
        Promise.all(promises).then(result => {
            resolve(result)
        })
    })
}

exports.loginJd = obj => {
    obj = obj || {}
    obj.index = obj.index || 0
    if (obj.index == jdChromeMngs.length) {
        return new Promise(resolve => {
            resolve()
        })
    }
    return new Promise((resolve, reject) => {
        getChromeMng(jdChromeMngs, obj).then(chromeMng => {
            chromeMng.loginJd(obj).then(result => {
                chromeMng.busy = false
                obj.index++
                exports.loginJd(obj).then(result => {
                    resolve(result)
                }, result => {
                    reject(result)
                })
            }, result => {
                chromeMng.busy = false
                reject(result)
            })
        })
    })
}

exports.getJdAdvLink = obj => {
    return new Promise((resolve, reject) => {
        getChromeMng(jdChromeMngs).then(chromeMng => {
            logger.debug('[' + __filename + ':' + __line + '] getJdAdvLink')
            chromeMng.getJdAdvLink(obj).then(result => {
                chromeMng.busy = false
                resolve(result)
            }, result => {
                chromeMng.busy = false
                reject(result)
            })
        }, result => {
            reject(result)
        })
    })
}

exports.getJdItems = obj => {
    return new Promise((resolve, reject) => {
        getChromeMng(jdChromeMngs).then(chromeMng => {
            chromeMng.getJdItems(obj).then(result => {
                chromeMng.busy = false
                resolve(result)
            }, result => {
                chromeMng.busy = false
                reject(result)
            })
        }, result => {
            reject(result)
        })
    })
}

exports.checkLoginJd = obj => {
    return new Promise((resolve, reject) => {
        getChromeMng(jdChromeMngs).then(chromeMng => {
            chromeMng.checkLoginJd(obj).then(result => {
                chromeMng.busy = false
                resolve(result)
            }, result => {
                chromeMng.busy = false
                reject(result)
            })
        }, result => {
            reject(result)
        })
    })
}

exports.getTaobaoBill = obj => {
    return new Promise((resolve, reject) => {
        getChromeMng(chromeMngs).then(chromeMng => {
            chromeMng.loginTaobao().then(async result => {
                //if (!result) {
                //    log('未登录淘宝联盟，释放chrome')
                //    chromeMng.busy = false
                //    reject('未登录淘宝联盟，释放chrome')
                //   return
                //}
                const {
                    Network,
                    Page,
                    DOM,
                    Runtime,
                    Emulation
                } = chromeMng.client;
                await Page.navigate({
                    url: 'https://pub.alimama.com/myunion.htm#!/report/detail/taoke?pageNo=1&payId=&timeId=1'
                })
                chromeMng.taobaoBill = []
                chromeMng.getTaobaoBillResolve = resolve
                chromeMng.getTaobaoBillReject = reject
                chromeMng.getTaobaoBillTimeout = setTimeout(() => {
                    chromeMng.busy = false
                    reject('获取淘宝订单超时，释放chrome')
                }, 30000)
            }, result => {
                chromeMng.busy = false
                reject(result)
            })
        }, result => {
            reject(result)
            logger.error('[' + __filename + ':' + __line + ']', result)
        })
    })
}

exports.getJdBill = obj => {
    return new Promise((resolve, reject) => {
        getChromeMng(jdChromeMngs).then(chromeMng => {
            chromeMng.checkLoginJd().then(result => {
                if (!result) {
                    log('未登录京东联盟，释放chrome')
                    reject('未登录京东联盟，释放chrome')
                    chromeMng.busy = false
                    return
                }
                const {
                    Network,
                    Page,
                    DOM,
                    Runtime,
                    Emulation
                } = chromeMng.client;
                Page.navigate({
                    url: 'https://media.jd.com/rest/report/detail'
                })
                chromeMng.jdBill = []
                chromeMng.getJdBillResolve = resolve
                chromeMng.getJdBillReject = reject
                // setTimeout(async () => {
                //     if (!chromeMng.busy) {
                //         return
                //     }
                //     var {result} = await Runtime.evaluate({expression: 'location.href'})
                //     if (!result.value.startsWith('https://media.jd.com/rest/report/detail')) {
                //         return
                //     }
                //     log('获取京东联盟订单，释放chrome')
                //     chromeMng.busy = false
                // }, 60000)
            }, result => {
                chromeMng.busy = false
                reject(result)
            })
        }, result => {
            reject(result)
        })
    })
}

exports.getTaobaoLoginQrcodes = () => {
    var qrcodes = []
    chromeMngs.forEach(chromeMng => {
        chromeMng.qrcode && qrcodes.push(chromeMng.qrcode)
    })
    return qrcodes
}

exports.getRedirectLink = obj => {
    return new Promise((resolve, reject) => {
        getChromeMng(chromeMngs).then(chromeMng => {
            chromeMng.getRedirectLink(obj).then(result => {
                chromeMng.busy = false
                resolve(result)
            }, result => {
                chromeMng.busy = false
                reject(result)
            })
        }, result => {
            reject(result)
        })
    })
}

exports.getWechatLoginQrcodes = () => {
    var qrcodes = []
    wechatChromeMngs.forEach(chromeMng => {
        qrcodes.push(chromeMng.qrcode)
    })
    return qrcodes
}

exports.sendWechatMsg = obj => {
    wechatChromeMngs[obj.from] && wechatChromeMngs[obj.from].send({
        who: obj.to,
        what: 'hi'
    })
}

exports.loginWechat = obj => {
    var promises = []
    for (var i = 0; i < wechatChromeMngs.length; i++) {
        promises.push(new Promise(resolve => {
            getChromeMng(wechatChromeMngs, {
                index: i
            }).then(chromeMng => {
                chromeMng.loginWechat().then(result => {
                    chromeMng.busy = false
                    resolve()
                }, result => {
                    chromeMng.busy = false
                    resolve()
                })
            }, result => {
                resolve()
            })
        }))
    }
    return new Promise((resolve, reject) => {
        Promise.all(promises).then(result => {
            resolve()
        })
    })
}

exports.getCode = obj => {
    for (var i = 0; i < chromeMngs.length; i++) {
        if (chromeMngs[i].code && chromeMngs[i].codeRequestId) {
            return new Promise(resolve => {
                resolve({
                    code: chromeMngs[i].code,
                    codeRequestId: chromeMngs[i].codeRequestId
                })
            })
        }
    }
    for (var i = 0; i < jdChromeMngs.length; i++) {
        if (jdChromeMngs[i].code && jdChromeMngs[i].codeRequestId) {
            return new Promise(resolve => {
                resolve({
                    code: jdChromeMngs[i].code,
                    codeRequestId: jdChromeMngs[i].codeRequestId
                })
            })
        }
    }
    return new Promise((resolve, reject) => {
        resolve({
            code: '',
            codeRequestId: ''
        })
    })
}

exports.submitCode = obj => {
    obj = obj || {}
    obj.codeRequestId = obj.codeRequestId || ''
    for (var i = 0; i < chromeMngs.length; i++) {
        if (obj.codeRequestId == chromeMngs[i].codeRequestId) {
            chromeMngs[i].codeText = obj.codeText
            return new Promise(resolve => {
                resolve()
            })
        }
    }
    for (var i = 0; i < jdChromeMngs.length; i++) {
        if (obj.codeRequestId == jdChromeMngs[i].codeRequestId) {
            jdChromeMngs[i].codeText = obj.codeText
            return new Promise(resolve => {
                resolve()
            })
        }
    }
    return new Promise((resolve, reject) => {
        resolve()
    })
}
